/*
 * @Description: 减签
 */
/*global workflowModule*/
import { useBaseInfoWithOut } from '@/store/modules/base-info';
import { useTemplateWithOut } from '@/store/modules/template';
import { useNodePermissionWithOut } from '@/store/modules/summary/node-permission';
// import { useSummaryCommentWithOut } from '@/store/modules/summary/comment';
import api from '@/api';
import {
  chooseHandle,
  getWorkflowData,
  getCollaborationParams,
  getFormData
} from './helper';
//自定义按钮数据更新
import customHandleDateUpdate from '../custom/helper';
//预归档到
import getPigeonhole, { pigeonholeHint } from '@/helper/pigeonhole';
//提交失败处理
import errHandle from '@/handles/common/err-handle';
import {fireEvent, getCollEventParams} from '@/handles/common/sdk';
//环形分支用。指定回退选态度\创建指定回退按钮数据
import { chooseAttitude } from '../return/helper';
import { createSpecifiesReturnBtn } from '../specifies-return';
//关闭窗口
import closeWindow from '@/helper/close';
import globalMethods from '@/plugins/methods';
import baseInfo from "@/components/classic-layout/create/base-info/index.vue";
import globalData from "@/plugins/data";
import {useBaseInfoStore} from "@/store/modules/base-info";
import publish from "@/handles/handle-list/summary/modules/systemAudit/publish";
import {APPLICATIONCATEGORYE} from "@/utils/const";

//基础信息
const useBaseInfo = useBaseInfoWithOut();
//正文信息
const useTemplate = useTemplateWithOut();
//协同信息
// const useSummaryComment = useSummaryCommentWithOut();
//节点权限
const useNodePermission = useNodePermissionWithOut();

export async function submit(btn, resolve = () => {}, needCheck = useBaseInfo.needCheckRule, weekSubmit = false) {
  //校验密级
  if (!useBaseInfo.checkSecret()) return resolve();
  //附件上传中
  if (!useBaseInfo.validateAttachmentUploading()) {
    return resolve();
  }
  //新闻公告审批 发布相关触发
  let submitHandleCode = btn.submitActionOriginal || btn.handleOriginal;
  if (submitHandleCode === 'ContinueSubmit' || submitHandleCode === 'bulletionAuditPass' || submitHandleCode === 'newsAuditPass'){
    // eslint-disable-next-line no-async-promise-executor
    let confirm = await new Promise(resolve1 => publish(btn,resolve1));
    if (!confirm){
      console.log('publish---------',confirm);
      return resolve();
    }
  }
  //拼装提交接口参数,不含表单数据
  const params = getCollaborationParams(btn);
  if (!params){
    return resolve();
  }

  //自定义按钮数据更新。将会更新封装了的流程或、态度
  if (btn.handle === 'custom' && !btn.skipBeforeInvokeWorkFlow) {
    await customHandleDateUpdate.call(
      this,
      params.collaborationDealParamData,
      btn,
      useBaseInfo.setIsHideGlobalLoading
    );
    //由于layer弹窗未提供点击取消按钮的回调。所以就里面直接先关闭弹窗，
    //resolve了在这里再打开
    useBaseInfo.setIsHideGlobalLoading(false);
  }
  // return;

  //不是暂存待办才校验
  const submitCode = params.collaborationDealParamData.submitCode;
  //不为暂存待办并且不需要再弹窗选择（目前已知情况：手动选择分支后提交的）
  if (submitCode !== 'Comment' && !btn.isNotShowDisagreeHandleList) {
    //如果态度是不同意，那么就校验是否有用户能够选择的不同意操作
    if (
      params.collaborationDealParamData.comment.attitude?.code === 'disagree' &&
      !!useNodePermission.disagreeAction.length
    ) {
      await chooseHandle.call(this, useNodePermission.disagreeAction, resolve);
    }
  }
  // 校验跟踪指定人
  if (submitCode !== 'Comment' && !useBaseInfo.validateTrackDeal()) return resolve();
  const formParamData = await getFormData(
    submitCode,
    submitCode !== 'Comment' && needCheck, //不是暂存待办就需要校验
    resolve
  );
  //表单数据读取失败了
  if (!formParamData){
    return resolve();
  }
  //设置表单数据
  params.formParamData={
    data:formParamData
  }
  //加入工作流信息。一开始不加入，因为有可能改变流程
  params.workflowParamData = getWorkflowData(formParamData);
  //环形分支不能退回的特殊处理
  if (btn.skipBeforeInvokeWorkFlow) {
    params.workflowParamData.workflowPreCommitInfo = {
      ...params.workflowParamData.workflowPreCommitInfo || {},
      skipBeforeInvokeWorkFlow: true
    }
  }
  //工作流事件的弱校验
  params.workflowParamData.weekSubmit = weekSubmit;
  //落款信息
  const {
    collaborationDealParamData: {
      dealDepartment = {}
    }, workflowParamData: {
      context = {}
    }
  } = params;
  context.postInfo = dealDepartment?.ids || '';
  //表单window对象
  const fnx = useTemplate.zwIframe.contentWindow;
  //有签章就调用签章保存，成功了再继续，失败了就不继续
  if (fnx.isHasISignFlag && fnx.isHasISignFlag() && !fnx.saveISignatureHtml()) return;
  //参考原逻辑提前
  if (submitCode === 'ContinueSubmit') {
    const businessData = useBaseInfoStore().baseInfo?.businessData || {};
    const eventParams = getCollEventParams(businessData, globalData, params);
    let result = await fireEvent("beforeDealSubmit", eventParams)
      .then((res) => {
        if (!res) {
          return Promise.resolve(false);
        }
        return fireEvent(submitCode, eventParams);
      });
    if (!result) {
      resolve();
      return;
    }
  }
  if (submitCode === 'Comment') {
    const businessData = useBaseInfoStore().baseInfo?.businessData || {};
    let hook = await fireEvent('doZCDB', getCollEventParams(businessData, globalData, params));
    if (!hook) {
      return;
    }
  }

  //如果勾选了预归档到，就弹出预归档弹窗，添加数据
  if (params.collaborationDealParamData.isPigeonhole) {
    //暂存待办提示
    if (submitCode === 'Comment') {
      await pigeonholeHint.call(this, resolve);
      //归档选择过了就不在归档了
    } else {
      if (useBaseInfo.pigeonholeId) {
        params.collaborationDealParamData.pigeonholeId = useBaseInfo.pigeonholeId;
      } else {
        //提交就弹出选择框
        params.collaborationDealParamData.pigeonholeId = (
          await getPigeonhole.call(this, resolve)
        ).value;
      }
    }
  }
  //开始保存正文 判断是否需要修改正文，isEditAttOrContent是协同外业务需要的
  let editAttOrContent = window.isEditAttOrContent;
  if (editAttOrContent && editAttOrContent !== 0) {
    //保存正文
    let promise = await new Promise((resolveCallBack) => {
      const { id } = useBaseInfo.baseInfo.businessData.summary;
      fnx.contentAPI.submit({
        checkNull: needCheck,
        mainbodyDomains: [],
        needCheckRepeatData: needCheck,
        needCheckRule: needCheck,
        needSn: needCheck,
        needSubmit: true,
        optType: submitCode,
        summaryId: id,
        failed: () => resolveCallBack(false),
        success: () => resolveCallBack(true)
      });
    });
    if (promise === false) {
      return resolve();
    }
  }
  console.log('提交数据', submitCode, params);
  try {
    const { code, data } = await api.summarySubmit(params);
    console.log(code, data);

    //需要手动选择分支
    if (code === 413) {
      const { passed, app, data: dataObj } = data || {};
      console.log(dataObj);
      if (!passed && dataObj) {
        const { data: errorObj } = dataObj[app];
        if (errorObj) {
          const {alertMessage,weakBlock} = errorObj;
          if (alertMessage && app === APPLICATIONCATEGORYE.WORKFLOW && !weakBlock) {
            window.$DialogBugReport(params.workflowParamData.context, "", alertMessage, () => resolve())
            /*globalMethods.warning({
              title: globalMethods.i18n('common.system.hint.label'),
              content: alertMessage,
            });*/
            return;
          }
        }
      }
      resolve();
      //看了下代码，工作流回调是这样。暂时这样，以后有机会可以修改为errHandle传参第二个参数
      workflowModule.context.fn = () => {
        btn.isNotShowDisagreeHandleList = true;
        btn.skipBeforeInvokeWorkFlow = true;
        defaultSubmit.call(this, btn);
      };

      //环形分支用-点确定
      window.stepBackToTargetNodeCallBack = (...args) => {
        const specifiesReturnBtn = createSpecifiesReturnBtn.call(this);
        specifiesReturnBtn.isCircleBack = true;
        chooseAttitude.call(this, specifiesReturnBtn, {
          appointStepBack: {
            theStepBackNodeId: args[4],
            submitStyle: args[5],
            isCircleBack: 1
          }
        });
      };
      //调这个方法，选完了会触发上面的回调 注意如果是工作流校验不通过，不会做执行下面的回调，直接走的workflowModule.context.fn
      errHandle(data, (...arg) => {
        const [result] = arg || [];
        if (!result) return;
        //工作流事件弱校验
        if (result.workflowEvent){
          submit.call(this, btn, resolve, useBaseInfo.needCheckRule, true)
          return;
        }
        //表单弱校验
        if (!result.isCwp) return;
        //已经确认过就不需要二次确认选择，场景：预提交提示表单、再提示工作流、又提示表单
        useBaseInfo.needCheckRule = false;
        submit.call(this, btn, resolve, useBaseInfo.needCheckRule);
      },
        (err)=>{
          console.log('send error', err);
          resolve();
        });
      return;
    }
    //流水号提示信息
    const { snInfoMsg } = data['1'] || {};
    if (snInfoMsg) {
      //额外的提示信息
      this.$success({
        content: snInfoMsg,
        onOk() {
          closeWindow();
        }
      });
      resolve();
      return;
    }
    this.$message.success({
      content: this.$i18n('collaboration.deal.success.title'),
      onClose: () => {
        resolve();
      }
    });

    closeWindow();
  } catch (e) {
    console.log('提交失败', e);
    resolve();
  }
}

export default function defaultSubmit(btn) {
  return new Promise((resolve) => {
    useBaseInfo.setIsHideGlobalLoading(false);
    //由于签章保存是同步操作，会阻碍页面渲染（渲染不出全局loading）
    //所以加个定时器，让它再下次宏任务执行，这一轮先渲染出loading
    setTimeout(async () => {
      await submit.call(this, btn, ()=>{
         useBaseInfo.setIsHideGlobalLoading();
         return  resolve(arguments);
      });
    });
  }).finally(() => {
    useBaseInfo.setIsHideGlobalLoading();
  });
}
